package com.ruoyi.quartz.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.flow.FlowTypeEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.dd.MessageUtil;
import com.ruoyi.common.utils.flow.FlowDTO;
import com.ruoyi.crm.domain.CrmOrder;
import com.ruoyi.crm.domain.CrmOrderCollectDetails;
import com.ruoyi.crm.domain.CrmOrderCollectPayMoney;
import com.ruoyi.crm.domain.CrmOrderPayDetails;
import com.ruoyi.crm.mapper.CrmOrderCollectDetailsMapper;
import com.ruoyi.crm.mapper.CrmOrderCollectPayMoneyMapper;
import com.ruoyi.crm.mapper.CrmOrderMapper;
import com.ruoyi.crm.mapper.CrmOrderPayDetailsMapper;
import com.ruoyi.crm.strategy.CrmOrderFlowStrategy;
import com.ruoyi.system.mapper.SysUserMapper;
import com.taobao.api.ApiException;
import com.warm.flow.core.entity.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {
    private static final Logger log = LoggerFactory.getLogger(RyTask.class);
    @Autowired
    private CrmOrderCollectPayMoneyMapper crmOrderCollectPayMoneyMapper;

    @Autowired
    private CrmOrderPayDetailsMapper crmOrderPayDetailsMapper;

    @Autowired
    private CrmOrderCollectDetailsMapper crmOrderCollectDetailsMapper;



    @Autowired
    private SysUserMapper userMapper;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() throws ApiException {
        //查询收付款 审核通过的
        List<CrmOrderCollectPayMoney> collectPayMonies = crmOrderCollectPayMoneyMapper.selectList(new LambdaQueryWrapper<CrmOrderCollectPayMoney>()
                .eq(CrmOrderCollectPayMoney::getFlowStatus, 8));
        if (StringUtils.isEmpty(collectPayMonies)) {
            log.info("--------无审核通过的数据---------------");
        }
        Map<String, List<CrmOrderCollectPayMoney>> map = collectPayMonies.stream().collect(Collectors.groupingBy(CrmOrderCollectPayMoney::getMoneyType));
        //收款容器
        List<CrmOrderCollectPayMoney> payList = map.get("1");
        if (StringUtils.isNotEmpty(payList)) {
            List<String> ids = payList.stream().map(CrmOrderCollectPayMoney::getCollectPayMoneyId).collect(Collectors.toList());
            List<CrmOrderCollectDetails> collectDetailsList = crmOrderCollectDetailsMapper.selectList(new LambdaQueryWrapper<CrmOrderCollectDetails>()
                    .in(CrmOrderCollectDetails::getCollectPayMoneyId, ids)
                    .eq(CrmOrderCollectDetails::getCollectDetailsStatus, 0));
            if (StringUtils.isNotEmpty(collectDetailsList)) {
                collectDetailsList.forEach(item -> {
                    //找到对应的主表的userId
                    List<CrmOrderCollectPayMoney> collected = payList.stream()
                            .filter(n -> n.getCollectPayMoneyId().equals(item.getCollectPayMoneyId()))
                            .collect(Collectors.toList());
                    CrmOrderCollectPayMoney collectPayMoney = collected.get(0);
                    isSend(item.getCollectDetailsTime(), collectPayMoney.getUserId(), collectPayMoney.getCollectPayMoneyId());
                });
            }

        }
//        //付款容器
//        List<CrmOrderCollectPayMoney> collectList = map.get("0");
//        if (StringUtils.isNotEmpty(collectList)) {
//            List<String> ids = collectList.stream().map(CrmOrderCollectPayMoney::getCollectPayMoneyId).collect(Collectors.toList());
//            List<CrmOrderPayDetails> collectDetailsList = crmOrderPayDetailsMapper.selectList(new LambdaQueryWrapper<CrmOrderPayDetails>()
//                    .in(CrmOrderPayDetails::getCollectPayMoneyId, ids)
//                    .eq(CrmOrderPayDetails::getPayDetailsStatus, 0));
//            if (StringUtils.isNotEmpty(collectDetailsList)) {
//                collectDetailsList.forEach(item -> {
//                    //找到对应的主表的userId
//                    List<CrmOrderPayDetails> collected = collectDetailsList.stream()
//                            .filter(n -> n.getCollectPayMoneyId().equals(item.getCollectPayMoneyId()))
//                            .collect(Collectors.toList());
//                    CrmOrderPayDetails crmOrderPayDetails = collected.get(0);
//                    isSend(item.getPayDetailsTime(), crmOrderPayDetails.getUserId(), crmOrderPayDetails.getCollectPayMoneyId());
//                });
//            }
//        }
        System.out.println("执行无参方法");
    }
    /**
     * 获取具体到期天数
     *
     * @author chenbinbin
     */
    private  void extracted(SysUser sysUser, int day, String collectPayMoneyId) throws ApiException {
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("markdown");
        msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
        msg.getMarkdown().setTitle("回款提醒");
        CrmOrderCollectPayMoney collectPayMoney = crmOrderCollectPayMoneyMapper.getById(collectPayMoneyId);
        String text = this.builder(collectPayMoney, sysUser, day);
        msg.getMarkdown().setText(text.toString());
        MessageUtil.send(sysUser.getUserId() + ",216565692120050668", msg);
//        MessageUtil.send( "216565692120050668", msg);


    }

    private String builder(CrmOrderCollectPayMoney collectPayMoney, SysUser user, int day){
        StringBuilder text = new StringBuilder();
        text.append("## " + collectPayMoney.getOrderName() + "的回款到期提醒");
        text.append("  \n  ");
        text.append("归属人：" + user.getUserName());
        text.append("  \n  ");
        if (day < 0) {
            text.append("超期天数：" + Math.abs(day));
        } else {
            text.append("剩余天数：" + day);
        }
        text.append("  \n  ");
        text.append("[立即查看](" + DDConstant.DD_FRONT_URL + DDConstant.FRONT_URL_HOST + "crm/crmOrderCollectPayMoney?active=collectPayMoneyMobile&collectPayMoneyId=" + collectPayMoney.getCollectPayMoneyId() + ")");
        return text.toString();
    }

    private void isSend(Date date, String userId, String id) {
        SysUser sysUser = userMapper.selectUserById(userId);
        int differentDay = DateUtils.differentDaysByMillisecondNotAbs(new Date(), date);
        if (differentDay == 45 || differentDay == 30 || differentDay <= 0) {
            try {
                //发送钉钉通知
                extracted(sysUser, differentDay, id);
                System.out.println("发送通知");
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
